<template>
    <el-form :model="question"  ref="ruleForm" class="question-content" label-width="90px" >
        <el-row :gutter="41">
            <el-col :span="12">
                <div class="form-item-title">
                    <span class="title-level">题目</span>
                </div>
                
                <el-row>
                    <el-col>
                        <el-form-item label="题目内容" prop="content" >
                            <div class="question-tit-content">
                                <Tinymce :toolbar="toolbar" :id="tinymceId" v-model="question.content" ref="tinymce" :width="500" :height='160' ></Tinymce>
                                <!-- <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" placeholder="请输入题目内容，最多500个汉字" v-model="question.content" :maxlength="500" resize="none"></el-input> -->
                                <!-- 上传展示的图片信息 -->
                                <!-- <div class="upload-pic-list">
                                    <ul class="upload-pit-list">
                                        <li class="attm-img">
                                            <p class="img">
                                                <img src="http://dl.xueleyun.com/images/1/200x200_511d7d316062154adda1d9e99149cd73.jpg">
                                            </p>
                                            <a href="javascript:;" class="close">
                                                <i class="el-icon-circle-close"></i>
                                            </a>
                                        </li>
                                    </ul>
                                </div> -->
                                <!-- 上传展示的图片信息 end -->
                            </div>
                            <el-button @click="insertFormula" type="text">插入公式</el-button>
                            <!-- <el-button type="text">插入图片</el-button> -->
                        </el-form-item>
                    </el-col> 
                </el-row>
                <question-options ref="questionOptions" @getOptions="getOptions"></question-options>
                <div class="form-item-title">
                    <span class="title-level">题目解析</span>
                </div>
                <el-row>
                    <el-col>
                         <el-form-item label="解析内容">
                            <div class="question-tit-content">
                                <Tinymce :toolbar="toolbar" :id="tinymceId1" v-model.trim="question.analysis" ref="tinymce1" :width="500" :height='160' ></Tinymce>
                            </div>
                            <el-button @click="insertFormula1" type="text">插入公式</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="form-item-title">
                    <span class="title-level">知识点</span>
                </div>
                <el-row >
                    <el-col>
                        <!-- <el-form-item label="已有知识点" prop="knowledge">
                            <tag v-for="(item,index) in tagList" :key="index" :addable="true" @add="subjectChange(item)">{{item.tagName}}</tag> 
                        </el-form-item> -->
                        <el-form-item label="关联知识点" prop="haveSubject">
                            <el-checkbox-group v-model="question.knowledgeTagList">
                                <el-checkbox :label="item.tagName" v-for="(item,index) in tagList" :key="index"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <!-- <el-form-item label="关联知识点" prop="haveSubject">
                            <div class="subjectKuang">
                                <el-tag :key="tag.name"  v-for="(tag,index) in question.knowledgeTagList" closable :disable-transitions="false"  @close="handleClose(index)">{{tag.tagName}}</el-tag>
                            </div>
                        </el-form-item> -->
                    </el-col> 
                </el-row>
                <div class="form-item-title">
                    <span class="title-level">属性标签</span>
                </div>
                <el-row>
                    <el-col>
                        <el-radio-group v-model="question.difficulty" >
                            <el-radio :label="1">容易</el-radio>
                            <el-radio :label="3">一般</el-radio>
                            <el-radio :label="5">困难</el-radio>
                        </el-radio-group>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="12">
                <div class="form-item-title">
                    <span class="title-level">题目预览</span>
                </div>
                <div class="preview min-w" v-show="showPriview">
                    <div class="type">
                        <span :class="{'active': isMultiselect.length == 1}">单选题</span>
                        <span :class="{'active': isMultiselect.length > 1}">多选题</span>
                    </div>
                    <div class="title" v-html="question.content"></div>
                    <div class="options">
                        <div class="option-item" :class="{'active': item.isCorrect == 'Y'}" v-for="(item,index) in optionsData" :key="index">
                            <div class="t" for="" v-text="optionsAllType[index] +'、'"></div>
                            <div class="c">
                                <span v-html="filterFormula(item.content)"></span>
                                <div class="img-list">
                                    <img :src="imgs.url" :key="index" v-for="(imgs,index) in item.optionsImg"/>
                                </div>
                            </div>
                        </div>        
                    </div>
                    <div class="analyze">
                        <p>解析：</p>
                        <div v-html="question.analysis" class="analyze-content"></div>
                    </div>
                   <div class="knowledge-list">
                        <span>关联知识点：</span>
                        <el-tag  v-for="(item,index) in question.knowledgeTagList" :key="index">{{item.tagName?item.tagName:item}}</el-tag>
                    </div>
                    <div class="knowledge-list">
                        <span>难度：</span>
                        <el-tag v-if="question.difficulty !== undefined">{{question.difficulty| showDifficultyTag }}</el-tag>
                    </div>
                </div>
                <div class="no-preview" v-show="!showPriview">
                    <div class="etm-preview">
                        <div class="empty">暂无题目预览</div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <div class="form-item">
            <el-form-item class="footer">
                <el-button @click="resetForm">取消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')" :disabled="optionsValidate" :loading="loadingBtn">处理完毕</el-button>
            </el-form-item>
        </div>
        <!-- 弹窗公式 -->
        <formula-dialog :clatex.sync="clatex" @getPicData="setDataPic"></formula-dialog>
        <!-- 弹窗公式 end -->
    </el-form> 
</template>

<script>
import { mapGetters} from 'vuex';
// import tag from 'components/tag';
// import { getQuestionInfo, updateQuestion, fuzzyListTag } from 'api/standardBank';
import { getProblemDetail, getProblemAnalysis, getAllTags, getQuestionTag} from 'api/modifyError.js';
import Tinymce from 'components/TinyText';
import questionOptions from './addNewQuestionOptions';
import FormulaDialog from './formulaDialog';
import Subject from './subject';
export default {
    name: 'addNewQuestionContent',
    components: {questionOptions, Tinymce, FormulaDialog, Subject},
    data() {
        return {
            updateAnalysis: '',
            question: {
                content: '',
                analysis: '',
                knowledge: '',
                knowledgeList: [ 
                    {
                        id: 0,
                        name: '拼音'
                    }
                ],
                knowledgeTagList: [
                    
                ], // 已有知识点
                difficulty: 3
            },
            loadingBtn: false,
            optionsData: [],
            optionsAllType: [...'ABCDEFGH'],
            toolbar: ['p bold italic underline'],
            // toolbar: ['p | bold italic| alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent '],
            clatex: false,
            tinymceId: 'tinymceId',
            tinymceId1: 'tinymceId1',
            currentSubject: '',
            tagName: '',
            tagList: [], // 知识点列表
            rules: {
                content: [
                     { required: true, message: '请输入题目内容', trigger: 'blur' }
                ]
            },
            contentTimer: null,
            maxonOff: true,
            maxonOff1: true,   
            type: null // 用来区分是题目正文还是解析解析内容  题目正文 = 1 , 解析内容 = 2
        }
    },
    created() {
        this.currentSubject = this.$route.params.subjectName;
        this.getKnowledgeTag();
        // console.log('this.official', this.official);
    },
    mounted() {
        if (this.isEdit()) {
            this.$emit('change', 'choice');
            this.getQuestionContent()
        }
    },
    watch: {
        'question.content'(val) {     
            this.checkContentLength(val, 1);       
        },
        'question.analysis'(val) {
            this.checkContentLength(val, 2);  
        }
    },
    computed: {
        ...mapGetters([
            'schoolId'
            // 'official'
        ]),
        isMultiselect() {
            let selectOptions = [];
            this.optionsData.forEach((item) => {
                if (item.isCorrect=='Y') {
                    selectOptions.push(item);
                }
            });
            return selectOptions;
        },
        showPriview() {
            return this.question.content.length > 0;
        },
        optionsValidate() {
            // if (this.question.content.length > 0&&this.optionsData.every((item) => item.content.trim().length > 0 && this.maxonOff && (item.content.trim().length > 0 && this.maxonOff1))) {
            //     return false
            // }
            if (this.question.content.length > 0 && this.optionsData.every((item) => (item.content.trim().length > 0 || item.optionsImg.length > 0)) && this.maxonOff && this.maxonOff1) {
                return false
            }
            return true;
        }
    },
    methods: {
        isEdit() {
            // var type = this.$route.params.type;
            // var flag = this.$route.params.flag;
            // console.log(this.$route);
            // if (type&&flag==1&&(type==12 || type==11)) {
            //     return true;
            // }
            return true;
        },
        // 判断题目和解析内容是否超过500字
        checkContentLength(val, flag) {
            clearTimeout(this.contentTimer);
            this.contentTimer = setTimeout(() => {
                // 替换html标签 img标签
                if (val) { 
                    console.log('hahahahahaha');
                    var content = val.replace(/<img[^>]*>/g, '').replace(/<(\w*)>(.*?)<\/\1>/g, function($1, $2, $3) {
                        return $3
                    });
                // 正则确定
                    var contentReg = /[a-z]+[\-\']?[a-z]*|[\u4e00-\u9fa5\w!@#$%^&*()（）、\-+\/,|\.，。！;；:：'"‘’“”【】？?]/ig;
                    content = content.match(contentReg);
                    if (content&&content.length > 500) {
                        this.$message.error('题目内容大于500字');
                        flag===1?this.maxonOff = false:this.maxonOff1 = false
                    
                    } else {
                        flag===1?this.maxonOff = true:this.maxonOff1 = true;
                    }
                }
            }, 200)
        },
        // 获取本章节所有知识点
        getKnowledgeTag() {
            let subjectName=this.$route.params.subjectName;
            let questionId=this.$route.params.questionId;
            getAllTags(subjectName, questionId).then(response => {
                this.tagList = response.data.content;
            })
        },
        // 选择知识点
        knowledgeChange() {
            console.log(1212);
        },
        // 删除知识点
        handleClose(index) {
            this.tagName = '';
            console.log(index);
            this.question.knowledgeTagList.splice(index, 1);
        },
        resetForm() {
            this.question.content = '';
            this.question.analysis='';
            this.$router.push({name: '题目纠错'});
        },
        getOptions(data) {
            this.optionsData = data;
            console.log('this.optionsData', this.optionsData)
        },
        setDataPic(data) {      
            if (this.type === 1) { // 题目内容
                this.$refs.tinymce.execCommand(data.priviewImg);
                this.$refs.tinymce.setContent(this.question.content);
                this.$refs.tinymce.moveToBookmark(this.bookMark);
            } else { // 解析内容
                this.$refs.tinymce1.execCommand(data.priviewImg);
                this.$refs.tinymce1.setContent(this.question.analysis);
                this.$refs.tinymce1.moveToBookmark(this.bookMark);  
            }
            
        },
        // 题目内容的插入公式
        insertFormula() { 
            this.clatex = true;
            this.bookMark = this.$refs.tinymce.getBookmark();
            this.type = 1;
        },
        // 题目解析的插入公式
        insertFormula1() {
            this.clatex = true;
            this.bookMark = this.$refs.tinymce1.getBookmark();
            this.type = 2;
        },
        submitForm(dataForm) {
            console.log(dataForm);
            let currentSubject = this.$route.params.subjectName;
            let importChapterId = this.$route.params.chapterId;
            // let importChapterName = this.$route.params.chapterName;
            let questionContent = this.question.content;
            let tags = [];
            let questionType = this.isMultiselect.length > 1 ? 12 : 11;
            let items = [];
            let questionId = this.$route.params.questionType;
            console.log('22222222222222222', questionContent);
            this.optionsData.forEach((item) => {
                var json = {
                    'content': item.content + (item.optionsImg&&item.optionsImg[0] ? ' <img src="'+ item.optionsImg[0] .url+'" class="wscnph"/>' : ''),
                    'isCorrect': item.isCorrect
                };
                if (item.id) {
                    json.id = item.id;
                }
                items.push(json)
            });

            this.question.knowledgeTagList.forEach((item) => {
                if (item.tagName) {
                    if (this.isEdit()) {
                        tags.push({'name': item.tagName});
    
                    } else {
                        tags.push(item.tagName);
                    }
                } else {
                    if (this.isEdit()) {
                        tags.push({'name': item});
    
                    } else {
                        tags.push(item);
                    }
                }
            });
                       
            this.$refs[dataForm].validate((valid) => {
                if (valid) {
                    let tempHtml = window.tinymce.get('tinymceId').getContent({format: 'raw'});
                    if (tempHtml.indexOf('img') === -1) {
                        if (!window.tinymce.get('tinymceId').getContent({format: 'text'}).trim()) {
                            this.$message('请输入题目内容');
                            return;
                        }
                        // var content = window.tinymce.get('tinymceId').getContent({format: 'text'}).replace(/<img[^>]*>/g, '').replace(/<(\w*)>(.*?)<\/\1>/g, function($1, $2, $3) {
                        //     return $3
                        // });
                        // // 正则确定
                        // var contentReg = /[a-z]+[\-\']?[a-z]*|[\u4e00-\u9fa5\w!@#$%^&*()（）、\-+\/,|\.，。！;；:：'"‘’“”【】？?]/ig;
                        // content = content.match(contentReg);
                        // // console.log(content, content.length, 'content-length');
                        // if (content&&content.length > 500) {
                        //     this.$message.error('题目内容大于500字');
                        //     return
                        // }
                        // if (window.tinymce.get('tinymceId').getContent({format: 'text'}).trim().length > 500) {
                        //     this.$message('选择题目内容不能大于500字');
                        //     return;
                        // }
                    }
                    if (this.isMultiselect.length <= 0) {
                        this.$message('至少勾选一个正确选项值');
                        return;
                    }

                    this.$confirm('确认发布?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    }).then(() => {
                        this.loading = true;
                        if (this.isEdit()) {
                            console.log('importChapterId', importChapterId);
                            this._updateQuestion(currentSubject, questionId, questionContent, items, tags, importChapterId, questionType, this.question.difficulty, this.schoolId, this.question.analysis);   
                        } 
                        // else {
                        //     console.log(1212);
                        //     this._createQuestion(currentSubject, importChapterId, importChapterName, questionContent, questionType, items, tags, this.question.difficulty, this.schoolId, this.question.analysis, this.official)
                        // }
                    }).catch(() => {
                        this.$message({type: 'info', message: '已取消'});          
                    });
                } else {
                    return false;
                }
            });
        },
        // _createQuestion(currentSubject, importChapterId, importChapterName, questionContent, questionType, items, tags, difficult, source, soluationContent, official) {
        //     createQuestion(currentSubject, importChapterId, importChapterName, questionContent, questionType, items, tags, difficult, source, soluationContent, official).then(response => {
        //         this.loading = false;
        //         if (response.data.status == 200) {
        //             this.$message.success(response.data.errorMsg);
        //             this.$refs['ruleForm'].resetFields();
        //             this.$store.dispatch('UpdateCache', true);
        //             this.$router.push({name: '题目纠错'});
        //         } else {
        //             this.$message.error(response.data.errorMsg);
        //         }
        //     }).catch(() => {
        //         this.loading = false;
        //     });
        // },
        _updateQuestion(currentSubject, questionId, questionContent, items, tags, importChapterId, questionType, difficult, source, soluationContent) {
            
            updateQuestion(currentSubject, questionId, questionContent, items, tags, importChapterId, questionType, difficult, source, soluationContent).then(response => {
                this.loading = false;
                if (response.data.status == 200) {
                    this.$message.success(response.data.errorMsg);
                    this.$refs['ruleForm'].resetFields();
                    this.$store.dispatch('UpdateCache', true);
                    this.$router.push({name: '题目纠错'});
                } else {
                    this.$message.error(response.data.errorMsg);
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        subjectChange(val) {
            for (let i=0;i<this.question.knowledgeTagList.length;i++) {
                if (val.tagName ===this.question.knowledgeTagList[i].tagName) {
                    this.$message({
                        type: 'warning',
                        message: '添加知识点重复'
                    });
                    return;
                }
            }
            if (val != '') {
                let tag = {
                    tagName: val.tagName,
                    tagId: val.tagId
                }
                this.question.knowledgeTagList.push(tag)
            }
        },
        filterFormula(val) {
            if (!val) return '';
            return val.replace(/\[LaTeXI\](.*?)\[\/LaTeXI\]/g, ($1, $2) => {

                return '<img src="http://gs.xueleyun.com//cgi-bin/mathtex.cgi?'+ $2 +'"/>';
            });
        },
        // 获取内容题目
        getQuestionContent() {
            let pId = this.$route.params.pId ;
            let subjectName=this.$route.params.subjectName;
            let questionId=this.$route.params.questionId;
            // console.log(pId, subjectName);
            getProblemDetail(pId, subjectName).then((response) => {
                // console.log(response);
                if (response.data.status == 200) {
                    this.setContent(response.data.content);          
                }
            })
            getProblemAnalysis(subjectName, questionId).then(response => {
                if (response.data.status==200) {
                    this.question.analysis = response.data.content?response.data.content.content:'';
                   
                }
            }) 
            
        },
        // 题目初始化处理
        setContent(data) {
            console.log(data);
            let optionData = [];
            this.question.content = data.question;
            let difficult = this.$route.params.difficult ;
            let subjectName=this.$route.params.subjectName;
            let questionId=this.$route.params.questionId;
            getQuestionTag(subjectName, questionId).then(response => {
                if (response.data.status==200) {
                    if (response.data.content) {
                        for (let i=0;i<response.data.content.length;i++) {
                            this.question.knowledgeTagList.push(response.data.content[i].tagName);
                        }
                    } else {
                        this.question.knowledgeTagList= [];
                    }
                }
                
            })
            this.question.difficulty =difficult?Number(difficult):0;
            
            data.listAnswer.forEach((item) => {

                var json = {
                    'id': item.answerId,
                    'content': item.content,
                    'isCorrect': item.iscorrect
                    // 'optionsImg': []
                }
                var reg = /src="([^"]*)/g;
                if (reg.test(item.content)) {
                    item.content.replace(reg, function($1, $2) {
                        json.optionsImg = [{name: '', url: $2}];
                    });
                } else {
                    json.optionsImg = [];
                }
                
                
                var arrContent = item.content.replace(/<img[^>]*>/g, '').replace(/<[^>]*>/g, '');
                // json.content = arrContent[0];
                json.content = arrContent;
                optionData.push(json)
            })
            this.optionsData = optionData;
            this.$refs.questionOptions.setOptionList(optionData);
        }
    },
    filters: {
        showDifficultyTag(val) {
            if (val === 1) {
                return '容易'
            } else if (val === 3) {
                return '一般'
            } else if (val ===5) {
                return '困难'
            } else {
                return '暂无'
            }
        }
    }

}
</script>

<style lang="scss">
@import '../../../../styles/var.scss';
.form-item-title{
    margin: 40px 0;
    font-size: 14px;
    color: #333;
    line-height: 14px;
    border-left: 4px solid #ff5e2c;
    text-indent: 16px;
}

.question-tit-content {
    // border: 1px solid #ccc;
    // box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.3);
    border-radius: 2px;
    .el-textarea__inner {
        box-shadow: none;
    }
    
}
.form-item-title:first-of-type{
        margin:20px 0;
}
.upload-pic-list {
    // padding: 5px;
    ul {
        overflow: hidden;
    }
    li {
        background: #f5f5f5;
        float: left;
        width: 110px;
        height: 110px;
        margin-right: 15px;
        font-size: 12px;
        padding: 12px!important;
        line-height: 21px;
        position: relative;
        margin-top: 15px;
        -moz-box-shadow: 0 1px 3px rgba(11,2,5,.16);
        -webkit-box-shadow: 0 1px 3px rgba(11,2,5,.16);
        box-shadow: 0 1px 3px rgba(11,2,5,.16);
    }
    .img {
        cursor: pointer;
        position: absolute;
        top: 0;
        left: 0;
        display: block;
        width: 100%;
        height: 100%;
        overflow: hidden;
        img {
            width: 100%;
            height: 100%;
            max-width: 100%;
            margin-top: -23px;
        }
    }
    .close {
        width: 20px;
        height: 20px;
        text-indent: -999px;
        overflow: hidden;
        position: absolute;
        top: -10px;
        right: -10px;
        background-image: url(../../../../images/home/close.png);
    }
}

.question-content{
    background:#fff;
    padding:10px 0 20px 20px;
    
}
.el-checkbox{
    margin-right:15px;
}
.el-tag{
    margin-left:10px;
    background:#f0f0f0;
    color:#444;
}
.form-item{
    padding-top:30px;
    text-align: center
}
.min-w {
    width: 600px;
}
.preview{
    padding-left:20px;
    overflow: hidden;
    .type{
        span{
            font-size:14px;
            display: inline-block;
            height: 28px;
            line-height: 28px;
            width: 80px;
            text-align: center;
            margin-right: 5px;
            color: #757575;
            background: #e0e0e0;
            -moz-border-radius: 3px;
            -webkit-border-radius: 3px;
            border-radius: 3px;

            &.active{
                background: #23c865;
                color: #fff;
            }
        }
    }
    .title{
        white-space:normal;
        word-break:break-all;
        padding-top:20px;
        font-size:14px;
        width: 410px; 
        .wscnph{
            max-width: 100px;
            margin: 5px;
            vertical-align: middle; 
        }
        img {
            max-width: 400px;
            margin: 5px;
            vertical-align: middle;
        }
    }
    .options{
        padding-top:15px;
        .option-item{
            padding-bottom: 5px;
            font-size:14px;
            height: auto;
            overflow: hidden;
            &.active{
            color: #07ba39; 
            }
            .t {
                float: left;
                width: 20px;
            }
            .c{
                // margin-top: 2px;
                float: left;
                width: 300px;
                line-height: 1.5;
                word-break: break-all;
            }
            img{
                max-width:400px;
                max-height:70px;
            }
        }
        .img-list {
            margin-top: 5px;
            img {
                height: 60px;
                margin-right: 5px;
            }
        }
    }
     .knowledge-list{ 
        float:left;
        padding-top: 15px;
        // width: calc(100% - 50px);
        width:100%;
        overflow-x: hidden;
        text-overflow:ellipsis;
        // white-space: nowrap;
        font-size:14px;

        .el-tag {
            // margin-bottom: 10px;
            margin:0 10px 10px 0;
        }

        .konowledge-item{
            border:$desc solid 1px;
            padding:2px 4px;
        }
    }
    .analyze{
        font-size:14px;
        padding-top:10px;
        width: 410px;
        color:#666;
        
        .analyze-content{
            white-space:normal;
            word-break:break-all;
            font-size:12px;
        }   

        img{
            max-width: 400px;
            margin: 5px;
            vertical-align: middle;
        }

        .wscnph{
                max-width: 100px;
        }
    }
}
.no-preview {
    height: 200px;
    width: 360px;
    .etm-preview {
        padding: 20px;
        .empty {
                background: url(../../../../assets/no-preview.png) center center no-repeat;
                padding: 150px 0 20px;
                text-align: center;
                color: #999;
        }
    }
}
</style>


